/**
 * 客户拉群
 */
import { UsergroupAddOutlined } from '@ant-design/icons'
import { useBoolean } from '@gnlab/utils/env-react'
import { Tooltip } from 'antd'
import { lazy } from 'react'
import { Modal } from '@/desktop/components'
import Tabs from '@/desktop/components/BeautyTabs'
import { Suspense } from '@/desktop/components/Loading'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import { ContactType, type Contact } from '@/services/contacts'
import './index.module.less'

const PullInNewGroup = lazy(async () => import('./ToNewGroup'))
const PullInExistGroup = lazy(async () => import('./ToExistGroup'))

export default function PullInGroup() {
  const [contact, receivedTransfers] = useStreams(
    services.contacts.current.contact,
    services.transfers.receiveList,
  )
  const [showing, show, hide] = useBoolean(false)

  if (
    contact === null ||
    contact.type !== ContactType.external ||
    receivedTransfers.has(contact.id) // TODO: 转交接收到的客户暂时不支持拉群
  ) {
    return null
  }

  return <div>
    <Tooltip title="拉群">
      <UsergroupAddOutlined onClick={show} />
    </Tooltip>

    <Modal
      title="客户拉群"
      styleName="pull-in-group"
      footer={null}
      width="60vw"
      open={showing}
      onCancel={hide}
    >
      <Suspense>
        <Content contact={contact} onCancel={hide} />
      </Suspense>
    </Modal>
  </div>
}

function Content(props: { contact: Contact; onCancel: () => void }) {
  const { contact, onCancel } = props

  const [tab, setTab] = useState('1')

  return <Tabs activeKey={tab} onChange={setTab}>
    <Tabs.TabPane tab="拉入现有群" key="1">
      {tab === '1' ? <PullInExistGroup contact={contact} onFinish={onCancel} /> : null}
    </Tabs.TabPane>
    <Tabs.TabPane tab="新建群" key="2">
      {tab === '2' ? <PullInNewGroup contact={contact} onCancel={onCancel} /> : null}
    </Tabs.TabPane>
  </Tabs>
}
